
import { ChangeEvent } from 'react'
import { Input, InputProps } from 'antd'
import './forms.scss'
import { useFormItemInit } from './hooks';
import { FormItemBaseProps } from './interface';
import { useDrag } from './drop.hooks';
import React from 'react';
import Readonly from './Readonly';
import { Utils } from '../../utils/utils';
import { Components } from '../..';




interface IProps extends FormItemBaseProps {
}

/** 延迟计时器 */
var timer: any = undefined;

export default function MyInput(props: IProps) {
    const { formControl, className = '', style = {} } = props;
    const {
        value, setValue,
        readonly,
        outerClassName,
        layout,
        placeholder,
        showError,
        outerStyle,
        labelStyle,
        selectorStyle,
    } = useFormItemInit(formControl, className, style);

    const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value;
        // 设置显示值
        setValue(val);
        // 延迟设置表单
        if (debounce > 10) {
            debounceSetFormValue(val);
        } else {
            formControl.setValue(val, 'user');
        }

        // formControl.setValue(val, 'user');
    };
    /** 延迟时间 单位 毫秒 */
    const debounce: number = formControl.controlData?.debounce ?? 0;
    /** 延迟设置表单 */
    const debounceSetFormValue = (val: any) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            formControl.setValue(val, 'user');
        }, debounce);
    }
    const inputProps: InputProps = {
        onChange: onInputChange,
        prefix: formControl.controlData.prefix,
        addonAfter: formControl.controlData.suffix ?? undefined,
        allowClear: formControl.controlData.resetBtn,
        size: formControl.controlData.size ?? 'middle', // large | middle | small
        className: `input`,
        status: showError ? 'error' : undefined,
        value: value,
        placeholder: (placeholder || '请输入'),
        maxLength: formControl.controlData.inputMaxlength,
        disabled: readonly,
        onPressEnter: (e) => {
            e.stopPropagation();
            if (Utils.isFunction(formControl.onPressEnter)) {
                formControl.onPressEnter!(e);
            }
        },
        styles: { 'input': selectorStyle },
    }

    /** 拖拽排序 */
    const dropRef = React.useRef<HTMLDivElement>(null);
    useDrag({ dropRef, formControl });

    return (
        <div component-name='form-item' className={`${outerClassName}`} style={outerStyle} ref={dropRef}>
            <div className={`field ${layout}`} >
                <Components.forms.FormLabel formControl={formControl} style={labelStyle} />
                <div className={`control`}>
                    <div className="value">
                        {
                            readonly ? <Readonly formControl={formControl} /> : <Input {...inputProps} />
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}
